﻿using AvalonAdmin.Attributes;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using System;
using System.Linq;

namespace AvalonAdmin.Converters
{
    /// <summary>
    /// 页面渲染
    /// </summary>
    public class ViewLocator : IDataTemplate
    {
        /// <summary>
        /// 生成页面
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public Control? Build(object? param)
        {
            if (param is null) return null;
            var name = param.GetType().Name;

            // 获取对象的所有属性和字段
            var viewModelType = param.GetType();
            var pathAttribute = viewModelType.GetCustomAttributes(typeof(PagePathAttribute), false)?.FirstOrDefault() as PagePathAttribute;
            if (pathAttribute != null)
            {
                name = pathAttribute.Path;
            }
            else if (name.IndexOf("ViewModel") > 0)
            {
                // 固定在AvalonAdmin.Pages.xxx.axaml的页面
                name = name.Replace("ViewModel", "");
            }
            else
            {
                // 自定义页面名称
                name = param.ToString();
            }

            var type = Type.GetType("AvalonAdmin.Pages." + name);
            if (type != null)
            {
                return (Control)Activator.CreateInstance(type)!;
            }
            return new TextBlock { Text = "Not Found: " + name };
        }

        public bool Match(object? data)
        {
            return true;
        }
    }
}